package com.cskaoyan.service.wx.impl;


import com.aliyun.oss.common.utils.DateUtil;
import com.cskaoyan.bean.wx.coupon.vo.CouponInfoVo;
import com.cskaoyan.bean.wx.coupon.vo.MyCouponVo;
import com.cskaoyan.bean.wx.order.bo.PageInfoBo;
import com.cskaoyan.mapper.CouponMapper;
import com.cskaoyan.mapper.CouponUserMapper;
import com.cskaoyan.service.wx.WxCouponService;
import com.cskaoyan.util.DateUtils;
import com.cskaoyan.util.GetUserIdUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.alibaba.druid.util.StringUtils;
import com.cskaoyan.bean.pojo.*;
import com.cskaoyan.bean.wx.coupon.ReceiveCouponBo;
import com.cskaoyan.bean.wx.coupon.SelectListVoEach;
import com.cskaoyan.mapper.CartMapper;
import com.cskaoyan.mapper.UserMapper;
import lombok.Data;
import lombok.SneakyThrows;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * @Name : WxCouponServiceImpl.java
 * @Time : 2021/8/16 11:45
 * @Author : Xfeng
 * @Software : IntelliJ IDEA
 */

/**
 * @Classname WxCouponController
 * @Description
 * @Date 2021/8/16 10:27
 * @Created by songweinan
 */

@Service
@Transactional
public class WxCouponServiceImpl implements WxCouponService {

    @Autowired
    private CouponMapper couponMapper;

    @Autowired
    private CouponUserMapper couponUserMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    CartMapper cartMapper;


    @Override
    public MyCouponVo mylist(Integer status, PageInfoBo pageInfoBo) {
        PageHelper.startPage(pageInfoBo.getPage(), pageInfoBo.getSize());

        Integer currentUserId = GetUserIdUtils.getCurrentUserId(userMapper);

        CouponUserExample couponUserExample = new CouponUserExample();
        CouponUserExample.Criteria criteria = couponUserExample.createCriteria();
        criteria.andDeletedEqualTo(false).andUserIdEqualTo(currentUserId);
        if (status != null && !status.equals("")) {
            criteria.andStatusEqualTo(new Short("" + status));
        }

        List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);
        List<CouponInfoVo> couponInfoList = new ArrayList<>();
        for (CouponUser couponUser : couponUsers) {
            Integer couponId = couponUser.getCouponId();
            Coupon coupon = couponMapper.selectByPrimaryKey(couponId);
            CouponInfoVo couponInfoVo = new CouponInfoVo(coupon.getMin(), coupon.getName(), coupon.getDiscount(), couponUser.getStartTime(), coupon.getId(), coupon.getTag(), couponUser.getEndTime(), coupon.getDesc(), coupon.getDays());
            couponInfoList.add(couponInfoVo);
        }

        PageInfo<CouponUser> couponUserPageInfo = new PageInfo<>(couponUsers);
        long total = couponUserPageInfo.getTotal();

        MyCouponVo myCouponVo = new MyCouponVo();
        myCouponVo.setData(couponInfoList);
        myCouponVo.setCount(total);
        return myCouponVo;
    }

    @Override
    public MyCouponVo list(PageInfoBo pageInfoBo) {
        PageHelper.startPage(pageInfoBo.getPage(), pageInfoBo.getSize());

        CouponExample couponExample = new CouponExample();
        CouponExample.Criteria criteria = couponExample.createCriteria();
        criteria.andDeletedEqualTo(false).andStatusEqualTo(new Short("0"));

        List<Coupon> coupons = couponMapper.selectByExample(couponExample);
        List<CouponInfoVo> couponInfoList = new ArrayList<>();
        for (Coupon coupon : coupons) {
            if(coupon.getTimeType() == 0){
                CouponInfoVo couponInfoVo = new CouponInfoVo(coupon.getMin(), coupon.getName(), coupon.getDiscount(), coupon.getStartTime(), coupon.getId(), coupon.getTag(), coupon.getEndTime(), coupon.getDesc(), coupon.getDays());
                couponInfoList.add(couponInfoVo);
            }
            if(coupon.getTimeType() == 1){
                CouponInfoVo couponInfoVo = new CouponInfoVo(coupon.getMin(), coupon.getName(), coupon.getDiscount(), coupon.getStartTime(), coupon.getId(), coupon.getTag(), coupon.getEndTime(), coupon.getDesc(), new Short("" + DateUtils.getDays(coupon.getStartTime(),coupon.getEndTime())));
                couponInfoList.add(couponInfoVo);
            }

        }

        PageInfo<Coupon> couponPageInfo = new PageInfo<>(coupons);
        long total = couponPageInfo.getTotal();

        MyCouponVo myCouponVo = new MyCouponVo();
        myCouponVo.setData(couponInfoList);
        myCouponVo.setCount(total);
        return myCouponVo;
    }

    @Override
    public List<SelectListVoEach> selectList(Integer cartId, Integer grouponRulesId) {

        Integer userId = getCurrentUserId();

        //先计算出当前用户订单的总额
        BigDecimal checkedGoodsTotalPrice = new BigDecimal(0);
        if (cartId != 0) {
            //fastadd的商品
            CartExample cartExample = new CartExample();
            CartExample.Criteria criteria = cartExample.createCriteria();
            criteria.andIdEqualTo(cartId);
            criteria.andDeletedEqualTo(false);
            List<Cart> carts = cartMapper.selectByExample(cartExample);
            Cart cart = carts.get(0);
            checkedGoodsTotalPrice = checkedGoodsTotalPrice.add(cart.getPrice().multiply(BigDecimal.valueOf(cart.getNumber())));
        } else {
            //cartId == 0
            CartExample cartExample = new CartExample();
            CartExample.Criteria criteria = cartExample.createCriteria();
            if (userId != null) {
                criteria.andUserIdEqualTo(userId);
            }
            criteria.andDeletedEqualTo(false);
            criteria.andCheckedEqualTo(true);

            List<Cart> cartList = cartMapper.selectByExample(cartExample);
            for (Cart cart : cartList) {
                checkedGoodsTotalPrice = checkedGoodsTotalPrice.add(cart.getPrice().multiply(BigDecimal.valueOf(cart.getNumber())));
            }
        }

        //查询当前用户可用优惠券
        CouponUserExample couponUserExample = new CouponUserExample();
        CouponUserExample.Criteria criteria = couponUserExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andStatusEqualTo((short) 0);
        criteria.andStartTimeLessThanOrEqualTo(new Date());
        criteria.andEndTimeGreaterThanOrEqualTo(new Date());
        criteria.andDeletedEqualTo(false);
        List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        List<SelectListVoEach> availableCouponList = new ArrayList<>();
        for (CouponUser couponUser : couponUsers) {
            Coupon coupon = couponMapper.selectByPrimaryKey(couponUser.getCouponId());
            if (checkedGoodsTotalPrice.compareTo(coupon.getMin()) > 0) {
                SelectListVoEach selectListVoEach = new SelectListVoEach(coupon.getId(), coupon.getName(), coupon.getDesc(), coupon.getTag(), coupon.getMin(), coupon.getDiscount(), sdf.format(couponUser.getStartTime()), sdf.format(couponUser.getEndTime()));
                availableCouponList.add(selectListVoEach);
            }
        }

        //无可用优惠券
        if (availableCouponList.size() == 0) {
            return null;
        }

        return availableCouponList;
    }

    /**
     * 领取优惠券（total limit type goods_type goods_value time_type）
     *
     * @param receiveCouponBo
     * @return
     */
    @SneakyThrows
    @Override
    public Integer receive(ReceiveCouponBo receiveCouponBo) {

        Integer userId = getCurrentUserId();

        //先从coupon获取优惠券相关信息
        CouponExample couponExample = new CouponExample();
        CouponExample.Criteria criteria1 = couponExample.createCriteria();
        criteria1.andIdEqualTo(receiveCouponBo.getCouponId());
        criteria1.andDeletedEqualTo(false);
        criteria1.andTypeEqualTo((short) 0);
        List<Coupon> coupons = couponMapper.selectByExample(couponExample);

        if (coupons == null || coupons.size() == 0) {
            //该优惠券不存在或已过期
            return 742;
        }

        Coupon coupon = coupons.get(0);


        //判断是否还可以领取(数量上)
        if (coupon.getTotal() == -1) {
            //优惠券已经领取完了
            return 741;
        }

        if (coupon.getTimeType() == 1) {
            //绝对日期的优惠券
            if (coupon.getStartTime().after(new Date()) || coupon.getEndTime().before(new Date())) {
                return 742;
                //不在领取时间  无法领取
            }
        }

        //相对日期的优惠券  创建时相对日期>=1 所以可以直接领取


        if (coupon.getLimit() != 0) {
            //需要判断是否已经领取超过limit限制
            CouponUserExample couponUserExample = new CouponUserExample();
            CouponUserExample.Criteria criteria = couponUserExample.createCriteria();
            criteria.andUserIdEqualTo(userId);
            criteria.andCouponIdEqualTo(receiveCouponBo.getCouponId());
            criteria.andDeletedEqualTo(false);
            List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);
            if (coupon.getLimit() - couponUsers.size() <= 0) {
                //已经领取超过上限
                return 740;
            }
        }

        //修改coupon中优惠券的数量  total为0表示该优惠券不限量 不用修改其total
        if (coupon.getTotal() != 0) {
            Coupon updateCoupon = new Coupon();
            updateCoupon.setId(coupon.getId());
            if (coupon.getTotal() == 1) {
                updateCoupon.setTotal(-1);
            } else {
                updateCoupon.setTotal(coupon.getTotal() - 1);
            }
            int i = couponMapper.updateByPrimaryKeySelective(updateCoupon);
        }

        //再将coupon插入couponUser
        CouponUser couponUser = new CouponUser();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date addTime = sdf.parse(sdf.format(new Date()));

        //给starttime和endtime赋值
        if (coupon.getTimeType() == 0) {
            //相对日期的优惠券
            Short days = coupon.getDays();
            couponUser.setStartTime(new Date());
            couponUser.setEndTime(DateUtils.getDateAfter(new Date(), days));
        } else {
            //绝对日期的优惠券
            couponUser.setStartTime(coupon.getStartTime());
            couponUser.setEndTime(coupon.getEndTime());
        }


        couponUser.setId(null);
        couponUser.setUserId(userId);
        couponUser.setCouponId(coupon.getId());
        couponUser.setStatus((short) 0);
        //couponUser.setStartTime(coupon.getStartTime());
        //couponUser.setEndTime(coupon.getEndTime());
        couponUser.setAddTime(addTime);
        couponUser.setUpdateTime(addTime);
        couponUser.setDeleted(false);
        int affectedRows = couponUserMapper.insertSelective(couponUser);

        return 200;
    }

    /**
     * 优惠券兑换
     *
     * @param exchangeCode
     * @return
     */
    @SneakyThrows
    @Override
    public Integer exchange(String exchangeCode) {

        Integer userId = getCurrentUserId();

        //首先查询是否有该优惠券
        CouponExample couponExample = new CouponExample();
        CouponExample.Criteria criteria = couponExample.createCriteria();
        if (!StringUtils.isEmpty(exchangeCode)) {
            criteria.andCodeEqualTo(exchangeCode);
        }
        criteria.andStatusEqualTo((short) 0);
        criteria.andTypeEqualTo((short) 2);
        criteria.andDeletedEqualTo(false);
        List<Coupon> coupons = couponMapper.selectByExample(couponExample);

        if (coupons == null || coupons.size() == 0) {
            //该优惠券不存在或已过期
            return 742;
        }

        //获得当前优惠券的信息
        Coupon coupon = coupons.get(0);
        if (coupon.getTotal() == -1) {
            //优惠券已经领取完了
            return 741;
        }

        if (coupon.getTimeType() == 1) {
            //绝对日期的优惠券
            if (coupon.getStartTime().after(new Date()) || coupon.getEndTime().before(new Date())) {
                return 742;
                //不在领取时间  无法领取
            }
        }

        //判断是否超过兑换上限
        if (coupon.getLimit() != 0) {
            CouponUserExample couponUserExample = new CouponUserExample();
            CouponUserExample.Criteria criteria1 = couponUserExample.createCriteria();
            criteria1.andCouponIdEqualTo(coupon.getId());
            criteria1.andUserIdEqualTo(userId);
            criteria1.andDeletedEqualTo(false);
            //查询当前用户所有改优惠券
            List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);
            for (CouponUser couponUser : couponUsers) {
                if (coupon.getLimit() - couponUsers.size() <= 0) {
                    //超过领取限制
                    return 740;
                }
            }
        }

        //领取优惠券并添加到couponUser表里
        //首先修改coupon表中数量 有数量限制的优惠券才需要修改
        if (coupon.getTotal() != 0) {
            Coupon updateCoupon = new Coupon();
            updateCoupon.setId(coupon.getId());
            if (coupon.getTotal() == 1) {
                updateCoupon.setTotal(-1);
            } else {
                updateCoupon.setTotal(coupon.getTotal() - 1);
            }
            int i = couponMapper.updateByPrimaryKeySelective(updateCoupon);
        }

        //将coupon插入couponUser
        CouponUser couponUser = new CouponUser();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date addTime = sdf.parse(sdf.format(new Date()));

        //给starttime和endtime赋值
        if (coupon.getTimeType() == 0) {
            //相对日期的优惠券
            Short days = coupon.getDays();
            couponUser.setStartTime(new Date());
            couponUser.setEndTime(DateUtils.getDateAfter(new Date(), days));
        } else {
            //绝对日期的优惠券
            couponUser.setStartTime(coupon.getStartTime());
            couponUser.setEndTime(coupon.getEndTime());
        }


        couponUser.setId(null);
        couponUser.setUserId(userId);
        couponUser.setCouponId(coupon.getId());
        couponUser.setStatus((short) 0);
        //couponUser.setStartTime(coupon.getStartTime());
        //couponUser.setEndTime(coupon.getEndTime());
        couponUser.setAddTime(addTime);
        couponUser.setUpdateTime(addTime);
        couponUser.setDeleted(false);
        int affectedRows = couponUserMapper.insertSelective(couponUser);

        return 200;
    }

    /**
     * 返回当前用户的用户id
     *
     * @return
     */
    private Integer getCurrentUserId() {

        String username = (String) SecurityUtils.getSubject().getPrincipal();
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        if (!StringUtils.isEmpty(username)) {
            criteria.andUsernameEqualTo(username);
        }
        criteria.andDeletedEqualTo(false);
        List<User> users = userMapper.selectByExample(userExample);
        return users.get(0).getId();
    }

}
